<template>
	<view class="page_wrapper">
		<Navbar title="在线测试"></Navbar>
		<view class="pagebox">
			<view class="first_row">
				<view class="use_time">
					<view style="padding-bottom: 24rpx;" class="first_title">{{useTimeTxt}}</view>
					<image src="https://www.hzif.cn/mathematics-attach/test_time.png" class="use_time_img"></image>
				</view>
				<view class="current_calc">
					<view class="first_title">{{currentCalcInx + 1}}/{{totalCount}}</view>
					<image src="https://www.hzif.cn/mathematics-attach/test_count.png" class="use_time_img"></image>
				</view>
			</view>
			<view class="first_block">
				<view class="second_row">
					<view>
						{{currentCalc.firstNum}} {{currentCalc.calcType}} {{currentCalc.secondNum}}
					</view>
					<view >=</view>
					<view class="result">
						{{currentResult}}
					</view>
					<view class="center_block">
						<!-- 竖式 -->
						<view class="help_block  my-anim" v-if="helpFlag" :class="{'animate__bounce': helpFlag , 'animate__backOutDown': !helpFlag}">
							<view class="help_wrapper">
								<view class="sign_col">{{currentCalc.calcType}}</view>
								<view class="val_col">
									<view>{{currentCalc.firstNum}}</view>
									<view>{{currentCalc.secondNum}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<image class="test_bg" src="https://www.hzif.cn/mathematics-attach/test_bg.png" mode=""></image>
			</view>
			
			<view class="calc_tips">计算时，孩子计算答案并说出答案，宝爸宝妈可帮小朋友配合输入答案，这样可以提高计算速度，一起体验计算的快乐~</view>
			<view class="bottom_block">
				<view class="nums_block">
					<view class="left_block">
						<view class="up_block">
							<view class="sub_left_block">
								<view class="key key_btn" @tap="showHelp()">{{helpFlagTxt}}</view>
								<view class="key key_btn pre_calc" @tap="toPreCalc()">上一题</view>
							</view>
							<view class="sub_right_block">
								<view class="sub_num_box">
									<view class="key num" @tap="keyDown('1')">1</view>
									<view class="key num" @tap="keyDown('2')">2</view>
									<view class="key num" @tap="keyDown('3')">3</view>
									<view class="key num" @tap="keyDown('4')">4</view>
									<view class="key num" @tap="keyDown('5')">5</view>
									<view class="key num" @tap="keyDown('6')">6</view>
									<view class="key num" @tap="keyDown('7')">7</view>
									<view class="key num" @tap="keyDown('8')">8</view>
									<view class="key num" @tap="keyDown('9')">9</view>
								</view>
								<view class="down_block">
									<view class="key zero" @tap="keyDown('0')">0</view>
									<view class="key dot" @tap="keyDown('.')">.</view>
								</view>
							</view>
						</view>
						
					</view>
					<view class="right_block">
						<view class="key key_btn" @tap="keyDown('-1')">退格</view>
						<view class="key_btn next_one" @tap="nextCalc()">下 一 题</view>
					</view>
				</view>
			</view>
		</view>
		<image class="page_bg_img" src="../../static/nimg/bg.png"></image>
	</view>
</template>

<script>
	import { getScore } from '../../utils/create'
import {request} from '@/utils/request.js'
	import {utils} from '@/utils/utils.js'
	import Navbar from '@/components/navbar.vue'
	export default {
		components:{
			Navbar
		},
		data() {
			return {
				running: false,
				examId: 0,
				mathExamWinId: 0,
				currentCalcInx: 0,
				calcList: [],
				currentCalc: {},
				totalCount: 0,
				currentResult: '',
				audioContext: null,
				timer: null,
				useTime: 0,
				useTimeTxt: '00:00',
				helpFlagTxt: '竖式开',
				helpFlag: false,
				isEdit:0,
				usedtime:0,
				isSave:false,
			}
		},
		onLoad(option) {
			this.examId = option.examId || 'test_id'
			this.isEdit = option.edit || 0
			this.usedtime = option.time || 0
			this.degreeLevel = option.degreeLevel
			this.mathExamWinId = option.mathExamWinId
			console.log(this.examId,option)
			if(this.degreeLevel){
				this.fetchTodayExam()
			}else if(this.mathExamWinId) {
				this.fetchMathExamWinData()
			} else if(this.examId) {
				this.fetchData()
			} 
		},
		onUnload(){
			clearInterval(this.timer)
			if(!this.isSave){
				const data = {
					'useTime': this.useTime,
					'calcList': JSON.stringify(this.calcList),
					'resultImg': '',
					'examType': 'online'
				}
				let arrs = getScore(data,this.examId)
				let that = this
				if(this.isEdit!=0){
					request.postJson("/topicRecordDetail/edit",{
						topicRecordId:that.examId,
						score:arrs[0].score,
						details:arrs[1],
						expendTime:Number(arrs[0].useTimeTxt)+that.usedtime,
						accuracy:arrs[0].accuracy,
						status:'1'
					}).then(res=>{
						if(res.code ===200){
							// uni.showToast({
							// 	title:'保存成功',
							// 	icon:'none'
							// })
						}
					})
				}else{
					request.postJson("/topicRecordDetail/save",{
						topicRecordId:that.examId,
						score:arrs[0].score,
						details:arrs[1],
						expendTime:arrs[0].useTimeTxt,
						accuracy:arrs[0].accuracy,
						status:'1'
					}).then(res=>{
						console.log(res);
						if(res.code ===200){
							// uni.showToast({
							// 	title:'保存成功',
							// 	icon:'none'
							// })
						}
					})
				}
			}
			
		},
		watch: {
			useTime(newValue, oldValue) {
				this.useTimeTxt = utils.int2Time(newValue)
			}
		},
		methods: {
			fetchData() {
				uni.showLoading()
				let that = this
				if(this.isEdit!=0){
					uni.hideLoading()
					request.get("/topicRecordDetail/list",{
						topicRecordId:that.examId,
						page:1,
						limit:60
					}).then(res=>{
						that.transformCalc(res.result.dataList)
					})
				}else{
					uni.getStorage({
						key:this.examId,
						success(res) {
							// 缓存里有当前id的试题
							console.log(res);
							if(res.errMsg ==="getStorage:ok"){
								uni.hideLoading()
								that.calcList = JSON.parse(res.data)
								that.calcList.forEach(item=>{
									if(item.myResult){
										that.currentCalcInx++
									}
								})
								that.totalCount = that.calcList.length
								that.currentCalc = that.calcList[that.currentCalcInx]
								that.timer = setInterval(() => {
									that.useTime++
								}, 1000)
							}
						},
						fail(err) {
							// 缓存里没有当前Id的试题
							uni.hideLoading()
							request.get("/topicRecordDetail/list",{
								topicRecordId:that.examId,
								page:1,
								limit:60
							}).then(res=>{
								console.log('asdfasdfs');
								that.transformCalc(res.result.dataList)
							})
						}
					})
				}
				
			},
			fetchMathExamWinData() {
				uni.showLoading()
			},
			fetchTodayExam() {
				uni.showLoading()
			},
			showHelp() {
				this.helpFlag = !this.helpFlag
				if(this.helpFlag) {
					// 显示
					this.helpFlagTxt = "竖式关"
				} else {
					// 隐藏
					this.helpFlagTxt = "竖式开"
				}
			},
			toPreCalc() {
				console.log('上一题')
				if( this.currentCalcInx -1 < 0){
					uni.showToast({ icon: 'none', title: '已经是第一题了' })
					return false
				}else {
					this.currentCalcInx--
					this.currentCalc = this.calcList[this.currentCalcInx]
					this.currentResult = this.currentCalc.myResult
				}
			},
			nextCalc() {
				// 判断结尾是不是有小数点
				const inx = this.currentResult.indexOf('.')
				if(inx >= 0 && inx === (this.currentResult.length - 1)) {
					// 存在. 并且在最后
					this.currentResult = this.currentResult.substring(0, this.currentResult.length -1)
				}
				// 保存当前答案
				this.calcList[this.currentCalcInx].myResult = this.currentResult
				if(this.currentCalcInx === (this.totalCount-1)){
					// 答题结束 保存结果
					uni.showLoading()
					this.isSave = true
					const data = {
						'useTime': this.useTime,
						'calcList': JSON.stringify(this.calcList),
						'resultImg': '',
						'examType': 'online'
					}
					let arrs = getScore(data,this.examId)
					let that = this
					if(this.isEdit!=0){
						this.editCalc(arrs,'2')
					}else{
						this.saveCalc(arrs,'2')
					}
					// 计算结果
				}else{
					this.currentCalcInx++
					this.currentCalc = this.calcList[this.currentCalcInx]
					this.currentResult = '0'
				}
				console.log(this.currentResult)
			},
			keyDown(val) {
				console.log(val)
				this.playClickMusic()
				if(val === '.' && this.currentResult.indexOf('.') >= 0) {
					return false
				}
				if(this.currentResult.indexOf('.') >= 0 && val !== '-1') {
					const startIndex = this.currentResult.indexOf('.')
					const len = this.currentResult.substring(startIndex+1)
					console.log(len)
					if(len.length >= 2) {
						uni.showToast({
							icon: 'none',
							title: '小数点后最多两位~'
						})
						return false
					}
				}
				if(this.currentResult.length > 5 && val !== '-1'){
					uni.showToast({
						icon: 'none',
						title: '值没有这么大~'
					})
					return false
				}
				if(val === '-1') {
					this.currentResult = this.currentResult.substring(0 , this.currentResult.length -1)
				} else {
					if(this.currentResult === '0' && val !== '.') {
						this.currentResult = val
					} else {
						this.currentResult = this.currentResult + val
					}
				}
				
				if(this.currentResult.length === 0) {
					this.currentResult = '0'
				}
				console.log(this.currentResult)
			},
			playClickMusic() {
				// const audioContext = uni.createInnerAudioContext()
				// audioContext.autoplay = true
				// audioContext.src = '/static/music/click.mp3'
			},
			editCalc(arrs,type){
				let that = this
				request.postJson("/topicRecordDetail/edit",{
					topicRecordId:that.examId,
					score:arrs[0].score,
					details:arrs[1],
					expendTime:Number(arrs[0].useTimeTxt)+that.usedtime,
					accuracy:arrs[0].accuracy,
					status:type
				}).then(res=>{
					if(res.code ===200){
						uni.setStorageSync('test_score',JSON.stringify(arrs[0]))
						uni.redirectTo({
							url: '/pages/mathCalcs/onlineFinished/onlineFinished?examId=' + that.examId
						})
					}
				})
			},
			saveCalc(arrs,type){
				let that = this
				request.postJson("/topicRecordDetail/save",{
					topicRecordId:that.examId,
					score:arrs[0].score,
					details:arrs[1],
					expendTime:arrs[0].useTimeTxt,
					accuracy:arrs[0].accuracy,
					status:type
				}).then(res=>{
					console.log(res);
					if(res.code ==200){
						uni.setStorageSync('test_score',JSON.stringify(arrs[0]))
						uni.redirectTo({
							url: '/pages/mathCalcs/onlineFinished/onlineFinished?examId=' + that.examId
						})
					}
				})
			},
			transformCalc(data){
				this.calcList = []
				let nreg = /[\+\-\*\/\=]+/
				let creg = /[^\+\-\*\/]+/
				if(data && data.length>0){
					data.forEach(item=>{
						const num = item.topic.split(nreg)
						const cas = item.topic.split(creg)
						console.log(item.topic,num,cas);
						let obj = {
							firstNum:num[0],
							secondNum:num[1],
							calcType:cas[1],
							id:item.id
						}
						if(item.userAnswer!=null){
							obj.myResult = item.userAnswer
							this.currentCalcInx++
						}
						this.calcList.push(obj)
					})
					this.totalCount = this.calcList.length
					this.currentCalc = this.calcList[this.currentCalcInx]
					this.timer = setInterval(() => {
						this.useTime++
					}, 1000)
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page_wrapper{
		.pagebox{
			padding: 0 30rpx;
		}
		.first_row{
			width: 100%;
			display: flex;
			justify-content: center;
			margin-top: 30rpx;
			.use_time_img{
				width: inherit;
				height: inherit;
			}
			.first_title{
				position: absolute;
				font-family:'eryaxinhei';
				font-size: 50rpx;
				padding-left: 60rpx;
				color: #FF4545;
				font-weight: 400;
			}
			.use_time{
				flex: 1;
				width: 384rpx;
				height: 118rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.current_calc{
				flex: 1;
				width: 300rpx;
				height: 93rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		.first_block{
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			border-radius: 5px;
			color: white;
			position: relative;
			.test_bg{
				height: 820rpx;
			}
			.second_row{
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				position: absolute;
				font-size: 100rpx;
				font-family: eryaxinhei;
				.result{
					color: #ffffff;
					height: 145rpx;
					width: 312rpx;
					background-color: #328372;
					border-radius: 20rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					overflow-x: auto;
				}
			}
		}
		.calc_tips{
			padding: 20rpx 10rpx 20rpx 10rpx;
			color: #2A6C5E;
			font-size: 24rpx;
			font-weight: 400;
		}
		.center_block{
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 100rpx;
			.help_block{
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				.help_wrapper{
					width:300rpx;
					border-bottom: 1px solid #FFFFFF;
					display: flex;
					align-items: flex-end;
					justify-content: center;
					.sign_col{
						padding-right: 20px;
						// background-color: red;
					}
					.val_col{
						// background-color: blue;
						letter-spacing: 15px;
						display: flex;
						flex-direction: column;
						align-items: flex-end;
					}
				}
				
			}
			
		}
		.bottom_block{
			font-family: eryaxinhei;
			color: #fff;
			.nums_block{
				flex: 1;
				display: flex;
				column-gap: 4rpx;
				.num{
					background-color:#36ac7a;
					border-radius: 10rpx;
					font-size: 66rpx;
					box-shadow: inset 0 0 5rpx 6rpx #56ce9b;
					text-shadow: -4rpx 1rpx 10rpx #00000055;
				}
				.key:active{
					background-color: #2A6C5E;
				}
				.key_btn{
					width: 100%;
					height: 100%;
					background-color: #36ac7a;
					border-radius: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					box-shadow: inset 0 0 5rpx 6rpx #56ce9b;
					text-shadow: -4rpx 1rpx 10rpx #00000055;
				}
				.left_block{
					display: flex;
					flex:0.8;
					.up_block{
						display: flex;
						flex: 1;
						column-gap: 4rpx;
						.sub_left_block{
							flex: 0.25;
							display: grid;
							grid-template-columns:repeat(1,1fr);
							grid-template-rows: repeat(3,1fr);
							grid-gap: 4rpx;
							font-size: 40rpx;
							.pre_calc{
								grid-row: span 2;
							}
						}
						.sub_right_block{
							display: flex;
							flex-direction: column;
							row-gap: 4rpx;
							flex: 0.75;
							text-align: center;
							.sub_num_box{
								display: grid;
								grid-template-columns: repeat(3,1fr);
								grid-gap: 4rpx;
								justify-self: center;
							}
						}
						
					}
					.down_block{
						display: grid;
						text-align: center;
						justify-self: center;
						grid-template-columns: repeat(3,1fr);
						grid-gap: 4rpx;
						font-size: 66rpx;
						.zero{
							background-color:#36ac7a;
							border-radius: 10rpx;
							flex: 0.65;
							grid-column: span 2;
							box-shadow: inset 0 0 5rpx 6rpx #56ce9b;
							text-shadow: -4rpx 1rpx 10rpx #00000055;
						}
						.dot{
							flex: 0.35;
							background-color:#36ac7a;
							border-radius: 10rpx;
							line-height:50rpx;
							box-shadow: inset 0 0 5rpx 6rpx #56ce9b;
							text-shadow: -4rpx 1rpx 10rpx #00000055;
							text-shadow: 0 0 5rpx 5rpx black;
						}
					}
					
				}
				.right_block{
					flex: 0.2;
					display: grid;
					grid-template-columns: repeat(1,1fr);
					grid-template-rows: repeat(3,1fr);
					grid-gap: 4rpx;
					font-size: 40rpx;
					.next_one{
						font-size: 38rpx;
						grid-row: span 2;
						background-color: #ff8835;
						box-shadow: inset 0 0 5rpx 6rpx #ffb030;
						text-shadow: -4rpx 1rpx 10rpx #00000055;
					}
				}
				.next_one:active{
					background-color: #ffb030;
				}
				
			}
		}
	}

</style>
